package com.ylkj.patient.ui.activities.webview;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.examination.mlib.constants.ARouterConstants;
import com.examination.mlib.constants.AllStringConstants;
import com.google.gson.Gson;
import com.examination.mlib.baseold.ModuleBaseActivity;
import com.examination.mlib.interfaceapi.NetWorkCallBack;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.network.https.interceptor.NetWorkUtils;
import com.yilijk.base.utils.LoadingUtils;
import com.ylkj.patient.R;
import com.ylkj.patient.entity.CustomeEntity;

import org.json.JSONException;
import org.json.JSONObject;

import crossoverone.statuslib.StatusUtil;

@Route(path = ARouterConstants.ContractWebviewActivity)
public class ContractWebviewActivity extends ModuleBaseActivity {
    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;
    private View webBack;
    private TextView webviewtitle;
    private WebView downloadBoring;
    @Autowired
    String title;
    @Autowired
    boolean isShowLoading;
    @Autowired
    String moorType;
    @Autowired
    String moorId;


    @Override
    public int bondLayout() {
        return R.layout.activity_web_view;
    }

    @Override
    public void initView() {
        if (isShowLoading) {
            LoadingUtils.getLoadingUtils(this).showLoading();
        }
        ARouter.getInstance().inject(this);   //注入
        //状态栏修改
        StatusUtil.setUseStatusBarColor(this, Color.WHITE);
        StatusUtil.setSystemStatus(this, false, true);
        webBack = findViewById(R.id.web_back);
        webviewtitle = findViewById(R.id.webviewtitle);
        downloadBoring = findViewById(R.id.download_boring);
        downloadBoring.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        /* 设置支持Js,必须设置的,基本大多数网页都涉及js */
        downloadBoring.getSettings().setJavaScriptEnabled(true);
        /* 设置为使用webview推荐的窗口，主要是为了配合下一个属性 */
        downloadBoring.getSettings().setUseWideViewPort(false);
        /* 设置网页自适应屏幕大小，该属性必须和上一属性配合使用 */
        downloadBoring.getSettings().setLoadWithOverviewMode(true);
//        配置webview保存密码选项
        downloadBoring.getSettings().setSavePassword(false);

        downloadBoring.addJavascriptInterface(new WebJavascriptInterface(this), "WebJavascriptInterface");
        downloadBoring.setWebViewClient(new ArticleWebViewClient());
        /* 设置是否允许webview使用缩放的功能 */
        //让缩放显示的最小值为起始
//        downloadBoring.setInitialScale(100);
        downloadBoring.getSettings().setTextZoom(100);
        downloadBoring.getSettings().setAllowFileAccess(true);
        downloadBoring.getSettings().setDomStorageEnabled(true);
        downloadBoring.getSettings().setBlockNetworkImage(false);
        downloadBoring.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        downloadBoring.getSettings().setLoadsImagesAutomatically(true);
        downloadBoring.getSettings().setSupportMultipleWindows(false);

        /* 设置是否允许webview使用缩放的功能 */
        //让缩放显示的最小值为起始
//        downloadBoring.setInitialScale(100);
        downloadBoring.getSettings().setMediaPlaybackRequiresUserGesture(false);
        downloadBoring.getSettings().setBuiltInZoomControls(true);
        downloadBoring.getSettings().setDisplayZoomControls(false); //隐藏webview缩放按钮
        webviewtitle.setText(title);
        downloadBoring.setWebChromeClient(new WebChromeClient() {//此行代码可以保证JavaScript的Alert弹窗正常弹出
            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> valueCallback) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android  >= 3.0
            public void openFileChooser(ValueCallback valueCallback, String acceptType) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android  >= 4.1
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
                openImageChooserActivity();
                return true;
            }
        });

        if (TextUtils.isEmpty(moorType)) {
            customerCommon();
        } else {
            switch (moorType) {
                case "common": {
                    customerCommon();
                    break;
                }
                case "doctor": {
                    if (!TextUtils.isEmpty(moorId)) {
                        customerDoctor(moorId);
                    } else {
                        customerCommon();
                    }
                    break;
                }
                case "drug": {
                    if (!TextUtils.isEmpty(moorId)) {
                        customerDrug(moorId);
                    } else {
                        customerCommon();
                    }
                    break;
                }
                case "packet": {
                    if (!TextUtils.isEmpty(moorId)) {
                        customerPacket(moorId);
                    } else {
                        customerCommon();
                    }
                    break;
                }
                case "order": {
                    if (!TextUtils.isEmpty(moorId)) {
                        customerOrder(moorId);
                    } else {
                        customerCommon();
                    }
                    break;
                }
                case "chargeOrder": {
                    if (!TextUtils.isEmpty(moorId)) {
                        customerChargeOrder(moorId);
                    } else {
                        customerCommon();
                    }
                    break;
                }
                default: {
                    customerCommon();
                    break;
                }
            }
        }

    }

    private void customerCommon() {
        HttpUtils.get(AllStringConstants.customer, new HttpCallBack<CustomeEntity>() {
            @Override
            public void onSuccess(CustomeEntity customeEntity, int i) {
                if (customeEntity.getStatus().equals("200")) {
                    downloadBoring.loadUrl(customeEntity.getData().getUrl());
                }
                LoadingUtils.getLoadingUtils(ContractWebviewActivity.this).dismissLoading();
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(ContractWebviewActivity.this).dismissLoading();

            }
        });
    }

    private void customerDoctor(String doctorId) {
        RequestParams params = new RequestParams();
        params.put("doctorId", doctorId);
        HttpUtils.get(AllStringConstants.customerDoctor, params, new HttpCallBack<CustomeEntity>() {
            @Override
            public void onSuccess(CustomeEntity customeEntity, int i) {
                if (customeEntity.getStatus().equals("200")) {
                    downloadBoring.loadUrl(customeEntity.getData().getUrl());
                }
                LoadingUtils.getLoadingUtils(ContractWebviewActivity.this).dismissLoading();
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(ContractWebviewActivity.this).dismissLoading();

            }
        });
    }

    private void customerDrug(String drugId) {
        RequestParams params = new RequestParams();
        params.put("drugId", drugId);
        HttpUtils.get(AllStringConstants.customerDrug, params, new HttpCallBack<CustomeEntity>() {
            @Override
            public void onSuccess(CustomeEntity customeEntity, int i) {
                if (customeEntity.getStatus().equals("200")) {
                    downloadBoring.loadUrl(customeEntity.getData().getUrl());
                }
                LoadingUtils.getLoadingUtils(ContractWebviewActivity.this).dismissLoading();
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(ContractWebviewActivity.this).dismissLoading();

            }
        });
    }

    private void customerPacket(String packetId) {
        RequestParams params = new RequestParams();
        params.put("packetId", packetId);
        HttpUtils.get(AllStringConstants.customerPacket, params, new HttpCallBack<CustomeEntity>() {
            @Override
            public void onSuccess(CustomeEntity customeEntity, int i) {
                if (customeEntity.getStatus().equals("200")) {
                    downloadBoring.loadUrl(customeEntity.getData().getUrl());
                }
                LoadingUtils.getLoadingUtils(ContractWebviewActivity.this).dismissLoading();
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(ContractWebviewActivity.this).dismissLoading();

            }
        });
    }

    private void customerOrder(String orderId) {
        RequestParams params = new RequestParams();
        params.put("orderId", orderId);
        HttpUtils.get(AllStringConstants.customerOrder, params, new HttpCallBack<CustomeEntity>() {
            @Override
            public void onSuccess(CustomeEntity customeEntity, int i) {
                if (customeEntity.getStatus().equals("200")) {
                    downloadBoring.loadUrl(customeEntity.getData().getUrl());
                }
                LoadingUtils.getLoadingUtils(ContractWebviewActivity.this).dismissLoading();
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(ContractWebviewActivity.this).dismissLoading();

            }
        });
    }

    private void customerChargeOrder(String orderId) {
        RequestParams params = new RequestParams();
        params.put("orderId", orderId);
        HttpUtils.get(AllStringConstants.customerChargeOrder, params, new HttpCallBack<CustomeEntity>() {
            @Override
            public void onSuccess(CustomeEntity customeEntity, int i) {
                if (customeEntity.getStatus().equals("200")) {
                    downloadBoring.loadUrl(customeEntity.getData().getUrl());
                }
                LoadingUtils.getLoadingUtils(ContractWebviewActivity.this).dismissLoading();
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(ContractWebviewActivity.this).dismissLoading();

            }
        });
    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {
        webBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        downloadBoring.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                LoadingUtils.getLoadingUtils(ContractWebviewActivity.this).dismissLoading();
            }
        });


    }

    /**
     * 打开本地图片
     */
    private void openImageChooserActivity() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

    private class ArticleWebViewClient extends WebViewClient {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            //重置webview中img标签的图片大小
            imgReset();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    /**
     * 对图片进行重置大小，宽度就是手机屏幕宽度，高度根据宽度比便自动缩放
     **/
    private void imgReset() {
        downloadBoring.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName('img'); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "var img = objs[i];   " +
                "    img.style.maxWidth = '100%'; img.style.height = 'auto';  " +
                "}" +
                "})()");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) {
                return;
            }
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null) {
                    results = new Uri[]{Uri.parse(dataString)};
                }
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }

}


